package com.studentexam.student.controller;

import com.studentexam.student.model.Student;
import com.studentexam.student.service.StudentService;
import com.studentexam.student.tool.ResponseMessage;
import com.studentexam.student.tool.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags="student")
@CrossOrigin
@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    @ApiOperation(value = "学生添加方法")
    @RequestMapping(value = "/addStudent", method = RequestMethod.GET)
    public ResponseMessage add(Student student) {
        int isAdd = 0;
//        1.判断是否空对象
        if (student != null) {
//        2.判断是否空字段
            if (student.getStudentnumber()!= null) {
//               3.添加数据
                isAdd = studentService.addStudent(student);
                if (isAdd==1){
                    return Result.success("保存成功");
                }else if (isAdd==-1){
                    return Result.success("已重复，不允许添加");
                }else return Result.error("保存失败");
            }
        }
        return Result.error("保存失败");
    }


    @ApiOperation(value = "学生信息删除方法")
    @RequestMapping(value = "/delStudent", method = RequestMethod.GET)
    public ResponseMessage delete(int studentid){
        if (studentid!=0){
            int isDel=0;
            isDel=studentService.delStudent(studentid);
            if (isDel>0){
                return Result.success("删除学生信息成功");
            }else return Result.error("删除学生信息失败");
        }else return Result.error("删除失败，学号不能为零");
    }

    @ApiOperation(value = "学生信息更新方法")
    @RequestMapping(value = "/updateStudent")
    public ResponseMessage update(Student student) {
        if (student != null) {
            if (student.getStudentid() != 0) {
                if (studentService.updateStudent(student) > 0) {
                    return Result.success("更新学生信息成功");
                } else return Result.error("更新学生信息失败");
            } else return Result.error("更新学生信息失败，学号不能为0");
        } else return Result.error("更新学生信息失败，此对象不能为空");
    }

    @ApiOperation(value = "根据条件获取学生信息")
    @RequestMapping(value = "/getByStudentid",method = RequestMethod.GET)
    public ResponseMessage getByStudentid(int studentid){
        Map<String, List> map=new HashMap<>();
        List<Student> studentList=studentService.getByStudentid(studentid);
        map.put("list",studentList);
        return Result.success("查询成功",map);
    }
}
